package top.jfunc.token.mem;

import top.jfunc.token.ErrorCountManager;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
 * 基于内存{@link ConcurrentHashMap}实现错误管理器
 * @author xiongshiyan at 2018/10/8 , contact me with email yanshixiong@126.com or phone 15208384257
 */
public abstract class BaseMemoryErrorCountManager<M> implements ErrorCountManager<M> {
    private Map<Object,Integer> map = new ConcurrentHashMap<>();
    private int threshold = 3;
    /**
     * 以秒为单位的过期时间
     */
    protected long expires  = 1800;

    @Override
    public int currentErrorCount(M member) {
        String key = key(member);
        return map.getOrDefault(key, 0);
    }

    @Override
    public int incrErrorCount(M member) {
        String key = key(member);
        Integer currentErrorCount = map.getOrDefault(key, 0);
        map.put(key, currentErrorCount+1);
        return currentErrorCount+1;
    }

    @Override
    public boolean reachThreshold(int currentErrorCount) {
        return currentErrorCount >= threshold;
    }

    @Override
    public void clearErrorCount(M member) {
        map.remove(key(member));
    }

    /**
     * 根据m获取key
     * @param member 实体
     */
    abstract protected String key(M member);

    public int getThreshold() {
        return threshold;
    }

    public void setThreshold(int threshold) {
        this.threshold = threshold;
    }

    public long getExpires() {
        return expires;
    }

    public void setExpires(long expires) {
        this.expires = expires;
    }
}
